package com.weiyuwqj.server.service.item.impl;

import com.github.pagehelper.PageHelper;
import com.weiyuwqj.api.exception.ExceptionMessage;
//import com.weiyuwqj.api.hengfeng.model.base.HfBaseResponseBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfResultBean;
//import com.weiyuwqj.api.hengfeng.model.platform.HfFundFreezeOrTraw;
import com.weiyuwqj.api.service.*;
import com.weiyuwqj.server.auto.BusItemAutoInvest;
//import com.weiyuwqj.server.pay.BidApi;
//import com.weiyuwqj.server.pay.InvestApi;
//import com.weiyuwqj.server.pay.PlatformApi;
import com.weiyuwqj.server.service.account.module.action.user.invest.*;
import com.weiyuwqj.server.mapper.*;
import com.weiyuwqj.api.constant.*;
import com.weiyuwqj.api.exception.HfException;
import com.weiyuwqj.api.model.vo.*;
//import com.weiyuwqj.api.hengfeng.param.vo.HfBidGrantVo;
//import com.weiyuwqj.api.hengfeng.param.vo.HfCreateBidVo;
import com.weiyuwqj.server.service.account.module.DealAction;
import com.weiyuwqj.server.service.account.module.DealModule;
import com.weiyuwqj.server.service.base.BaseServiceImpl;
import com.weiyuwqj.api.common.Calculator;
import com.weiyuwqj.api.common.PageList;
import com.weiyuwqj.api.common.Paginator;
import com.weiyuwqj.api.common.RepayPlan;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.model.*;
import com.weiyuwqj.api.util.*;
import com.weiyuwqj.server.service.finance.module.OperateModule;
import com.weiyuwqj.server.service.finance.module.action.ExpendOperateAction;
import com.weiyuwqj.server.service.finance.module.action.IncomeOperateAction;
import com.weiyuwqj.server.service.finance.module.action.OperateAction;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by zhangyong on 2016/8/5.
 */
@Service("itemService")
public class BasItemServiceImpl extends BaseServiceImpl<BasItem> implements BasItemService {
    private static Logger logs = Logger.getLogger("BasItemServiceImpl");

    private static final BigDecimal Zero = new BigDecimal(0);

    private static final String SERIAL_NUMBER = "XXX"; // 流水号格式

    @Autowired
    private BasItemMapper itemMapper;
    @Autowired
    private BusItemInvestMapper investMapper;
    @Autowired
    private BusItemCollectMapper collectMapper;
    @Autowired
    private BusVerifyLogMapper verifyLogMapper;
    @Autowired
    private BusItemRepayMapper repayMapper;
    @Autowired
    private BusAccountMapper accountMapper;
    @Autowired
    private BasCouponMapper couponMapper;
    @Autowired
    private DealModule dealModule;
    @Autowired
    private BasUserMapper userMapper;
    @Autowired
    private BusIncomeStatMapper incomeStatMapper;
    @Autowired
    private SysPictureMapper pictureMapper;
    @Autowired
    private BasTicketMapper ticketMapper;
    @Autowired
    private BasUserSecurityMapper userSecurityMapper;
    @Autowired
    private BasAssetsPackageMapper assetsPackageMapper;
    @Autowired
    private BusAssetPackagePlanMapper busAssetPackagePlanMapper;
    @Autowired
    private BusAccountBankService accountBankService;
    @Autowired
    private BasUserSecurityService userSecurityService;
    @Autowired
    private BusItemAutoInvest autoInvest;
    @Autowired
    private OperateModule operateModule;
//    @Autowired
//    private BidApi bidApi;
//    @Autowired
//    private PlatformApi platformApi;
//    @Autowired
//    private InvestApi investApi;

    //后台列表
    @Override
    public PageList getList(Paginator p, Map map) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        List<BasItemVo> list = itemMapper.getList(map);
        return new PageList(list);
    }

    //后台导出列表
    @Override
    public List<BasItemVo> getList(Map map) {
        return itemMapper.getList(map);
    }

    //统计发布项目数量
    @Override
    public Integer countByAllItemNum(Map map) {
        return itemMapper.countByAllItemNum(map);
    }

    //统计发布项目金额
    @Override
    public Double sumByAllItemAccount(Map map) {
        return itemMapper.sumByAllItemAccount(map);
    }

    //统计已还款的项目
    @Override
    public Integer countByRepayItem(Map map) {
        return itemMapper.countByRepayItem(map);
    }

    //统计未还款的项目
    @Override
    public Integer countByNoRepayItem(Map map) {
        return itemMapper.countByNoRepayItem(map);
    }

    //待初审项目数量
    @Override
    public Integer countByFirstItemNum(Map map) {
        return itemMapper.countByFirstItemNum(map);
    }

    //待初审项目金额
    @Override
    public Double sumByFirstItemAccount(Map map) {
        return itemMapper.sumByFirstItemAccount(map);
    }

    @Override
    public Double sumNoRepayItemAccount(Map map) {
        return itemMapper.sumNoRepayItemAccount(map);
    }

    @Override
    public Double sumRepayItemAccount(Map map) {
        return itemMapper.sumRepayItemAccount(map);
    }

    /**
     * app推荐标
     *
     * @return app推荐标
     */
    @Override
    public List<BasItemVo> queryRecomendList() {
        List<BasItemVo> recomendList = itemMapper.queryRecomendList();
        if (recomendList == null || recomendList.size() == 0) {
            return null;
        }
        for (BasItemVo basItemVo : recomendList) {
            Date date = new Date();
            long a = 0L;
            if (basItemVo.getReleaseTime() != null) {
                a = basItemVo.getReleaseTime().getTime();
            }
            long b = date.getTime();
            long d = a - b;
            if (d < 0) {
                itemMapper.updateItemStatus(ItemStatus.WAITOPEN, ItemStatus.OPEN, basItemVo.getId());
            }
            basItemVo.setCountdown(d);
        }
        return recomendList;
    }


    //截标
    @Override
    public void interceptItem(Integer itemId) {
        itemMapper.updateItemStatus(ItemStatus.OPEN, ItemStatus.INTERCEPT_COMPLETE, itemId);
    }

    @Override
    public void updateItemStatus(@Param("oldStatus") int oldStatus, @Param("newStatus") int newStatus, @Param("itemId") Integer itemId) {

        itemMapper.updateItemStatus(oldStatus, newStatus, itemId);
    }

//    //初审
//    @Override
//    public Object firstVerify(int itemId, BusVerify verify, Integer countdown, String releaseTime, Integer itemType) {
//        BasItem item = itemMapper.selectByPrimaryKey(itemId);
//        String itemNumber = StringUtils.getOrderNo();
//        if (item.getItemStatus() != ItemStatus.NEW) {
//            throw new CrowdException("item.status.not_open");
//        }
//        if (verify.getVerifyStatus() == 2) {
//            //审核失败
//            Integer oldStatus = item.getItemStatus();
//            itemMapper.updateItemStatus(oldStatus, ItemStatus.FAILURE, itemId);
//            itemMapper.updateItemIsalive(0, itemId);
//            return Message.OK;
//        }
//        HfCreateBidVo createBidVo = new HfCreateBidVo();
//        createBidVo.setItemNumber(itemNumber); // 项目编号
//        createBidVo.setBidId(itemId+"");
//        createBidVo.setAmount(item.getItemAccount().multiply(new BigDecimal(100)).longValue());
//        createBidVo.setBidRate(item.getItemRate().add(item.getItemAddRate()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_EVEN).toString());
//        //查询借款人信息
//        BasUserSecurity security = userSecurityMapper.getOneByUserId(item.getItemUserId());
//        if (null != security) {
//            createBidVo.setBorrCertNo(security.getIdentifyCard());
//            createBidVo.setBorrName(security.getRealname());
//            createBidVo.setUserType(1);
//        }
//        createBidVo.setBorrPurpose(item.getItemLoanUse()); // 借款用途
//        if (item.getItemCycleUnit() == 1) {
//            createBidVo.setCycle(item.getItemCycle().toString());
//        } else {
//            createBidVo.setCycle(item.getItemCycle() * 30 + "");
//        }
//        createBidVo.setCycleUnit(item.getItemCycleUnit().toString()); // 周期单位
//        createBidVo.setMinLimitAmount(item.getItemSingleMinInvestment().longValue());
//        createBidVo.setName(item.getItemName());//标名
//        createBidVo.setUserId(item.getItemUserId().toString()); // 用户ID
//        createBidVo.setBorrName(userSecurityService.getOneByUserId(item.getItemUserId()).getRealname()); // 借款人名称
//        createBidVo.setItemNumber(itemNumber); // 订单号
//        createBidVo.setReleaseTime(item.getReleaseTime());
//        //createBidVo.setInterestTime(item.getInvestTimes());
//        if (item.getItemRepayMethod() == 1) {
//            createBidVo.setRepaymentType("0");
//        } else {
//            createBidVo.setRepaymentType("1");
//        }
//        if (countdown == 1) {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Date date = null;
//            try {
//                date = sdf.parse(releaseTime);
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//            if (date.getTime() - new Date().getTime() < 0) {
//                throw new CrowdException("item.first.time.error");
//            }
//            Map<String, Object> releaseTimeMap = new HashMap<String, Object>();
//            releaseTimeMap.put("releaseTime", date);
//            releaseTimeMap.put("itemId", itemId);
//            itemMapper.modifyReleaseTimeByItemId(releaseTimeMap);
//        }
//        //更新项目编号
//        itemMapper.updateItemNumberByItemId(itemNumber,itemId);
//        BasUser user = userMapper.selectByPrimaryKey(item.getItemUserId());
//        createBidVo.setPlatfromId(user.getPlatformId());
//        BusAccountBank accountBank = accountBankService.getOneByUserId(item.getItemUserId());
//        HfResultBean resultBean = bidApi.createBid(createBidVo, accountBank);// 发标请求
//        //"{"data":{"prod_id":"1532185611111"},"recode":"10000","remsg":"成功","signdata":"aed7f9c05297d9f676a735cad0ee5beb"}"
//        //{"recode":"20016","remsg":"订单号重复","signdata":"3915624e537518373321d142c15b43ea"}
//        //String signdata = map.get("signdata").toString(); // 签名
//        //if (!resultBean.isSuccess()) { // 当且仅当返回码为10000时表示请求成功
//        //    throw new HfException("HfException", resultBean.getMessageText());
//        //}
//        item = itemMapper.selectByPrimaryKey(itemId);
//        if (item.getReleaseTime() != null) {
//            long time = item.getReleaseTime().getTime() - new Date().getTime();
//            if (time >= 0) {
//                itemMapper.updateItemStatus(ItemStatus.NEW, ItemStatus.WAITOPEN, itemId);
//            } else {
//                if (itemType == 1) autoInvest.busItemMatchingAutoRule(item);
//                itemMapper.updateItemStatus(ItemStatus.NEW, ItemStatus.OPEN, itemId);
//            }
//        } else {
//            Map releaseTimeMap = new HashMap();
//            releaseTimeMap.put("releaseTime", new Date());
//            releaseTimeMap.put("itemId", itemId);
//            itemMapper.modifyReleaseTimeByItemId(releaseTimeMap);
//            //处理自动投标后将项目激活,更新isalive=1
//            if (itemType == 1) autoInvest.busItemMatchingAutoRule(item);
//            itemMapper.updateItemIsalive(1, itemId);
//            itemMapper.updateItemStatus(ItemStatus.NEW, ItemStatus.OPEN, item.getId());
//        }
//        BusVerifyLog log = new BusVerifyLog();
//        log.setOperateUserId(1);
//        log.setContent("项目初审");
//        log.setAddtime(new Date());
//        log.setType((byte) 2);
//        log.setItemId(itemId);
//        log.setStatus((byte) 1);
//        log.setAddip(IpUtils.get());
//        verifyLogMapper.insert(log);
//        return Message.OK;
//    }

//    /**
//     * 批量投资
//     *
//     * @param item
//     * @param investList
//     * @return
//     */
//    public Map batchInvest(BasItem item, List<BusItemInvest> investList) {
//        //批量投资
//        List<BatchInvestVo> batchInvestVos = new ArrayList<>();
//        for (BusItemInvest itemInvest : investList) {
//            //查询红包
//            BasCoupon coupon = couponMapper.getCouponByInvestId(itemInvest.getId());
//            //查询用户信息
//            BasUser user = userMapper.selectByPrimaryKey(itemInvest.getUserId());
//            BatchInvestVo batchInvestVo = new BatchInvestVo();
//            if (null == coupon) {
//                batchInvestVo.setCouponAmt("0");
//            } else {
//                batchInvestVo.setCouponAmt(coupon.getAmount().toString());
//            }
//            batchInvestVo.setDetailNo(itemInvest.getInvestOrder());
//            batchInvestVo.setExperienceAmt("0");
//            batchInvestVo.setInInterest("0");
//            batchInvestVo.setSelfAmt(itemInvest.getInvestDealAmount().toString());
//            batchInvestVo.setUser(user);
//            batchInvestVos.add(batchInvestVo);
//        }
//        //请求恒丰
//        HfResultBean result = investApi.createInvest(batchInvestVos, item);
//        if (!result.isSuccess()) {
//            Map resultMap = new HashMap();
//            resultMap.put("result", "fail");
//            resultMap.put("messageText", result.getMessageText());
//            return resultMap;
//        }
//
//        //修改项目状态
//        itemMapper.modifyItemFullStatusByItemId(2, 1, item.getId());
//        return Message.OK;
//    }

//    /**
//     * 项目成标
//     *
//     * @param itemId
//     * @param item
//     * @param investList
//     */
//    public void creatBid(int itemId, BasItem item, List<BusItemInvest> investList) {
//        Integer oldStatus = item.getItemStatus(); // 标当前状态
//        itemMapper.updateItemStatus(oldStatus, ItemStatus.FULL_AUDIT, itemId); // 更新标状态
//        //投资人动作
//        BusItemInvest itemInvest = new BusItemInvest();
//        itemInvest.setItemId(itemId);
//        BigDecimal itemPrincial = BigDecimal.ZERO;
//        BigDecimal itemInterest = BigDecimal.ZERO;
//
//        //统计每个投资的人的分期数据
//        List<BigDecimal[]> princialList = new ArrayList<BigDecimal[]>(investList.size());
//        List<BigDecimal[]> interestList = new ArrayList<>(investList.size());
//        List<BigDecimal[]> additionalList = new ArrayList<>(investList.size());
//
//        Date verifyDatetime = DateUtils.setDayLast(new Date());
//        for (int i = 0; i < investList.size(); i++) {
//            BusItemInvest invest = investList.get(i);
//            List<RepayPlan> repayPlanList = Calculator.getPlanTime(invest.getInvestDealAmount(), item);//项目利率的
//
//            //根据investId查询加息券信息
//            BasTicket ticket = ticketMapper.getOneByInvestId(invest.getId());
//
//            List<RepayPlan> addRateAmount;//项目利率加上加息券利率
//            BasItem addRateItem = new BasItem();
//            BeanUtils.copyProperties(item, addRateItem);
//            if (null != ticket) {
//                addRateAmount = Calculator.getPlanTime(invest.getInvestDealAmount(), item);//项目利率的
//                //计算加息收益
//                Integer usefulLife = ticket.getUsefulLife();
//                if (usefulLife > item.getItemCycle()) {
//                    usefulLife = item.getItemCycle();
//                }
//                addRateItem.setItemCycle(usefulLife);
//                addRateItem.setItemRate(ticket.getRate());
//                addRateItem.setItemAddRate(BigDecimal.ZERO);
//                //计算总收益
//                BigDecimal totalTicketInterest = Calculator.addRateInterest(invest.getInvestDealAmount(), addRateItem);
//                for (int k = 0; k < addRateAmount.size(); k++) {
//                    if (k == addRateAmount.size() - 1) {
//                        RepayPlan plan = addRateAmount.get(k);
//                        plan.setInterest(plan.getInterest().add(totalTicketInterest));
//                        plan.setAccount(plan.getPrincipal().add(plan.getInterest()));
//                    }
//                }
//            } else {
//                addRateAmount = Calculator.getPlanTime(invest.getInvestDealAmount(), item);
//            }
//            BigDecimal investPrincial = BigDecimal.ZERO;
//            BigDecimal investInterest = BigDecimal.ZERO;
//            BigDecimal investAdditionalRateAmount = BigDecimal.ZERO;
//            BigDecimal[] princialCollectArray = new BigDecimal[repayPlanList.size()];
//            BigDecimal[] interestCollectArray = new BigDecimal[repayPlanList.size()];
//            BigDecimal[] additionalCollectArray = new BigDecimal[repayPlanList.size()];
//            for (int j = 0; j < repayPlanList.size(); j++) {
//                RepayPlan plan = repayPlanList.get(j);
//                RepayPlan addRatePlan = addRateAmount.get(j);
//                BusItemCollect collect = new BusItemCollect();
//                collect.setAdditionalRateAmount(addRatePlan.getInterest().subtract(plan.getInterest()));
//                collect.setItemId(itemId);
//                collect.setCollectAmount(addRatePlan.getAccount());
//                collect.setCollectTotalPeriod(repayPlanList.size());
//                collect.setCollectCurrentPeriod(addRatePlan.getPeriod());
//                collect.setCollectPrincipal(addRatePlan.getPrincipal());
//                collect.setCollectInterest(addRatePlan.getInterest());
//                collect.setCollectTime(plan.getEndTime());
//                collect.setActualCollectAmount(BigDecimal.ZERO);
//                collect.setActualCollectPrincipal(BigDecimal.ZERO);
//                collect.setActualCollectInterest(BigDecimal.ZERO);
//                collect.setAddip(IpUtils.get());
//                collect.setAddtime(new Date());
//                collect.setInvestId(invest.getId());
//                collect.setInvestUserId(invest.getUserId());
//                collect.setCollectStatus(0);
//                collect.setDebtTransferStatus(0);
//                collect.setPlatformId(userMapper.selectByPrimaryKey(invest.getUserId()).getPlatformId());
//                collectMapper.insert(collect);
//                princialCollectArray[j] = plan.getPrincipal();
//                interestCollectArray[j] = plan.getInterest();
//                additionalCollectArray[j] = addRatePlan.getInterest().subtract(plan.getInterest());
//                //repayTimeCollectArray[j]=plan.getEndTime();
//                investInterest = investInterest.add(addRatePlan.getInterest());
//                investPrincial = investPrincial.add(addRatePlan.getPrincipal());
//                investAdditionalRateAmount = investAdditionalRateAmount.add(addRatePlan.getInterest().subtract(plan.getInterest()));
//            }
//
//            princialList.add(princialCollectArray);
//            interestList.add(interestCollectArray);
//            additionalList.add(additionalCollectArray);
//            //repayTimeList.add(repayTimeCollectArray);
//
//            //投标时已经计算预计回收金额、利息，现在清0重新计算，以复审后为准
//            invest.setCollectAmount(BigDecimal.ZERO);
//            invest.setCollectInterest(BigDecimal.ZERO);
//            invest.setCollectPrincipal(BigDecimal.ZERO);
//
//            investMapper.updateItemInvestStatus(0, 1, invest.getId());
//            investMapper.updateItemFullInvestCollet(investPrincial, investInterest, invest.getId(), investAdditionalRateAmount);
//
//            itemPrincial = itemPrincial.add(investPrincial);
//            itemInterest = itemInterest.add(investInterest);
//
//            DealAction deduct = new InvestDeductDealAction();
//            deduct.deal(invest.getUserId(), investPrincial, "扣除" + item.getItemName() + "项目投资冻结资金");
//            dealModule.dealAction(deduct);
//
//            DealAction wait = new GenerateWaitDealAction();
//            wait.deal(invest.getUserId(), investPrincial.add(investInterest), item.getItemName() + "产生待收资金,加息券金额为" + investAdditionalRateAmount + "元");
//            dealModule.dealAction(wait);
//
//            //复审通过使income_stat表修改待收
//            BusItemInvest busItemInvest = investList.get(i);
//            Map<String, Object> updateMap = new HashMap<String, Object>();
//            updateMap.put("waitIncome", investInterest);
//            updateMap.put("userId", busItemInvest.getUserId());
//            updateMap.put("earnedIncome", 0);
//            updateMap.put("totalIncome", investInterest);
//            incomeStatMapper.updateByWaitEarned(updateMap);
//        }
//        //借款人动作
//        if (princialList.size() > 0) {
//            int planLength = princialList.get(0).length;
//            BigDecimal sumRepay = BigDecimal.ZERO;//总待还
//            BasUser user = userMapper.selectByPrimaryKey(item.getItemUserId()); // 获取用户信息
//            for (int j = 0; j < planLength; j++) {
//                BigDecimal princial = BigDecimal.ZERO;
//                BigDecimal interest = BigDecimal.ZERO;
//                BigDecimal additional = BigDecimal.ZERO;
//                for (int i = 0; i < princialList.size(); i++) {
//                    BigDecimal[] pa = princialList.get(i);
//                    BigDecimal[] ia = interestList.get(i);
//                    BigDecimal[] ad = additionalList.get(i);
//                    princial = princial.add(pa[j]);
//                    interest = interest.add(ia[j]);
//                    additional = additional.add(ad[j]);
//                }
//                BusItemRepay repay = new BusItemRepay();
//                BigDecimal amount = princial.add(interest);
//                repay.setRepayUserId(item.getItemUserId());
//                repay.setRepayAmount(amount);
//                repay.setRepayPrincipal(princial);
//                repay.setAdditionalRateAmount(additional);
//                repay.setRepayInterest(interest);
//                repay.setItemId(itemId);
//                repay.setRepayCurrentPeriod(j + 1);
//                repay.setRepayTotalPeriod(planLength);
//                repay.setStatus(0);
//                repay.setActualRepayAmount(BigDecimal.ZERO);
//                repay.setActualRepayInterest(BigDecimal.ZERO);
//                repay.setActualRepayPrincipal(BigDecimal.ZERO);
//                repay.setOrderNo(StringUtils.getOrderNo());
////                  repay.setRepayTime(DateUtils.addTime(item.getItemCycleUnit(), DateUtils.setDayLast(verifyDatetime), item.getItemCycle()));
//                repay.setRepayTime(DateUtils.addTime(1, DateUtils.setDayLast(verifyDatetime), (j + 1) * 30));
//                repay.setPlatformId(user.getPlatformId()); // 设置平台ID
//                repayMapper.insert(repay);
//                sumRepay = sumRepay.add(amount);
//            }
//            //借款人收到资金
//            DealAction receiveAction = new ReceiveLendDealAction();
//            receiveAction.deal(item.getItemUserId(), item.getItemOngoingAccount(), "收到" + item.getItemName() + "项目资金" + item.getItemOngoingAccount() + "元");
//            int receiveCount = dealModule.dealAction(receiveAction);
//            if (receiveCount < 1) {
//                throw new CrowdException("update_error");
//            }
//
//            String orderNo = RandomCodesUtils.createRandom(true, 8) + itemId; // 生成放款订单号
//            //插入资金明细记录
//            OperateAction operate = new IncomeOperateAction();
//            operate.operateAction(orderNo, OperateContants.BORROWER_CREDIT,itemId,
//                    item.getItemName(),item.getItemOngoingAccount());
//            operateModule.operateAction(operate);
//
//            //借款人增加项目待还
//            DealAction repayAction = new RepayAmountDealAction();
//            repayAction.deal(item.getItemUserId(), sumRepay, item.getItemName() + "产生待还金额");
//            int repayCount = dealModule.dealAction(repayAction);
//            if (repayCount < 1) {
//                throw new CrowdException("update_error");
//            }
//            //放款
//            BigDecimal sum = BigDecimal.ZERO;
//            for (BusItemInvest busItemInvest : investList) {
//                sum = sum.add(busItemInvest.getInvestDealAmount()); // 实际成交金额
//            }
//
//            HfBidGrantVo bidGrantVo = new HfBidGrantVo();
//            bidGrantVo.setBidId(itemId + ""); // 标ID
//            bidGrantVo.setTotalNum(investList.size());
//            bidGrantVo.setTotalAmount(sum.multiply(new BigDecimal(100)).longValue());
//            bidGrantVo.setUserId(item.getItemUserId().toString());
//            bidGrantVo.setOrderId(orderNo); // 放款订单号
//            bidGrantVo.setGrantAmount(BigDecimal.ONE.longValue()); // 放款总金额=投资订单总金额
//            bidGrantVo.setAmount(sum.multiply(new BigDecimal(100)).subtract(BigDecimal.ONE).longValue());// 分润金额
//            bidGrantVo.setSubOrderId(orderNo + "FR");// 分润单Id
//            //bidGrantVo.setReceiveUserId(item.getGuaranteeId().toString());//分润收款用户Id
//            //恒丰接口
//            List<BusItemRepay> itemRepays = repayMapper.getRepayListsByItemIdAndCurrentPeriod(itemId);
//            HfResultBean result = investApi.bidGrant(bidGrantVo, itemRepays);// 成标
//            //{"recode":"20016","remsg":"订单号重复","signdata":"3915624e537518373321d142c15b43ea"}
//            // 返回码，10000为成功; remsg:返回结果描述; data:返回业务数据; 商户请求订单号;    订单状态0:已接受,1:处理中,2:处理成功,3:处理失败;  系统处理日期(yyyyMMddHHmmss));    平台流水号;  签名数据
//            // {"recode":"10000","remsg":"成功","data":{"order_no":"xxx","order_status":"xxx","process_date":"xxx","query_id":"xxx"},"signdata":""}
//            //if (!result.isSuccess()) { // 当且仅当返回码为10000时表示请求成功
//            //    throw new HfException("HfError", result.getMessageText());
//            //}
//        }
//        //项目信息更新
//        itemMapper.updateItemStatus(ItemStatus.FULL_AUDIT, ItemStatus.REPAYING, itemId);
//
//        BusVerifyLog log = new BusVerifyLog();
//        log.setOperateUserId(1);
//        log.setAddip(IpUtils.get());
//        log.setType((byte) 4);
//        log.setItemId(itemId);
//        log.setAddtime(new Date());
//        log.setStatus((byte) 1);
//        log.setContent("项目复审");
//        verifyLogMapper.insert(log);
//
//        oldStatus = item.getItemStatus();
//        itemMapper.updateItemStatus(oldStatus, ItemStatus.REPAYING, itemId);
//
//        //修改项目状态
//        itemMapper.modifyItemFullStatusByItemId(3, 2, itemId);
//    }

    @Override
    public List<BasItem> getItemListByPackageId(Integer packageId) {
        return itemMapper.getItemListByPackageId(packageId);
    }

    @Override
    public PageList checkAccountList(Paginator p, Map map) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        List<AccountCheckingVo> list = itemMapper.checkAccountList(map);
        for (AccountCheckingVo checkingVo : list) {
            AccountCheckingVo repay=repayMapper.getStatByItemId(checkingVo.getId());
            AccountCheckingVo collect=collectMapper.getStatByItemId(checkingVo.getId());
            checkingVo.setRecivedAmount(repay.getRecivedAmount());
            checkingVo.setRecivedPrincipal(repay.getRecivedPrincipal());
            checkingVo.setRecivedInterest(repay.getRecivedInterest());
            checkingVo.setRestReciveAmount(repay.getRestReciveAmount());
            checkingVo.setRestRecivePrincipal(repay.getRestRecivePrincipal());
            checkingVo.setRestReciveInterest(repay.getRestReciveInterest());
            checkingVo.setPeriods(repay.getPeriods());
            checkingVo.setPaidAmount(collect.getPaidAmount());
            checkingVo.setPaidPrincipal(collect.getPaidPrincipal());
            checkingVo.setPaidInterest(collect.getPaidInterest());
            checkingVo.setRestPayAmount(collect.getRestPayAmount());
            checkingVo.setRestPayPrincipal(collect.getRestPayPrincipal());
            checkingVo.setRestPayInterest(collect.getRestPayInterest());
        }
        return new PageList(list);
    }

    @Override
    public List<AccountCheckingVo> checkAccountList(Map map) {
        List<AccountCheckingVo> list = itemMapper.checkAccountList(map);
        for (AccountCheckingVo checkingVo : list) {
            AccountCheckingVo repay=repayMapper.getStatByItemId(checkingVo.getId());
            AccountCheckingVo collect=collectMapper.getStatByItemId(checkingVo.getId());
            checkingVo.setRecivedAmount(repay.getRecivedAmount());
            checkingVo.setRecivedPrincipal(repay.getRecivedPrincipal());
            checkingVo.setRecivedInterest(repay.getRecivedInterest());
            checkingVo.setRestReciveAmount(repay.getRestReciveAmount());
            checkingVo.setRestRecivePrincipal(repay.getRestRecivePrincipal());
            checkingVo.setRestReciveInterest(repay.getRestReciveInterest());
            checkingVo.setPeriods(repay.getPeriods());
            checkingVo.setPaidAmount(collect.getPaidAmount());
            checkingVo.setPaidPrincipal(collect.getPaidPrincipal());
            checkingVo.setPaidInterest(collect.getPaidInterest());
            checkingVo.setRestPayAmount(collect.getRestPayAmount());
            checkingVo.setRestPayPrincipal(collect.getRestPayPrincipal());
            checkingVo.setRestPayInterest(collect.getRestPayInterest());
        }
        return list;
    }

    @Override
    public Map checkAccountStat(Map map) {
        return itemMapper.checkAccountStat(map);
    }

    /**
     * app项目和包计划列表
     * @return
     */
    @Override
    public PageList itemAndPackagePlanList(Paginator p) {
        PageHelper.startPage(p.getPageNum(),p.getPageSize());
        List<ItemAndPlanVO> list = itemMapper.getItemAndPackagePlanList();
        for (int i = 0; i < list.size(); i++) {
            ItemAndPlanVO item = list.get(i);
            Date date = new Date();
            long a = 0L;
            if (item.getReleaseTime() != null) {
                a = item.getReleaseTime().getTime();
            }
            long b = date.getTime();
            long d = a - b;
            if (d <= 0) {
                itemMapper.updateItemStatus(ItemStatus.WAITOPEN, ItemStatus.OPEN, item.getId());
            }
            item.setCountdown(d);
        }
        return new PageList(list);
    }

//    /**
//     * 解冻操作
//     *
//     * @param investList 投资列表
//     * @return
//     */
//    public Object thawBoolean(List<BusItemInvest> investList, Integer itemId) {
//        //是否完成解冻开关
//        Boolean thaw = true;
//        //操作解冻
//        for (BusItemInvest itemInvest : investList) {
//            BasCoupon coupon = couponMapper.getCouponByInvestId(itemInvest.getId());
//            HfFundFreezeOrTraw freezeOrTraw = new HfFundFreezeOrTraw();
//            if (coupon != null) {
//                freezeOrTraw.setAmount(itemInvest.getInvestDealAmount().subtract(coupon.getAmount()).toString());
//            } else {
//                freezeOrTraw.setAmount(itemInvest.getInvestDealAmount().toString());
//            }
//            freezeOrTraw.setFreeze_order_no(itemInvest.getFreezeOrderNo());
//            freezeOrTraw.setFreeze_flg("02");
//            freezeOrTraw.setPlatcust(userMapper.selectByPrimaryKey(itemInvest.getUserId()).getPlatformId());
//            freezeOrTraw.setRemark(itemInvest.getUserId().toString());
//            freezeOrTraw.setOrder_no(StringUtils.getOrderNo());
//            try {
//                HfResultBean result = platformApi.doFundFreeze(freezeOrTraw);
//            } catch (Exception e) {
//                thaw = false;
//            }
//        }
//        if (!thaw) {
//            throw new CrowdException("item.recall.thaw_error");
//        }
//
//        if (null != itemId) {
//            //修改项目复审状态
//            itemMapper.modifyItemFullStatusByItemId(1, 0, itemId);
//        }
//        return Message.OK;
//    }


//    /**
//     * 撤标
//     *
//     * @param itemId
//     */
//    public Object cancel(int itemId) {
//        //查询标信息
//        BasItem item = itemMapper.selectByPrimaryKey(itemId);
//        HfResultBean result = investApi.bidCancel(item);// 标取消
//        // {"recode":"40001","remsg":"无效的产品id","signdata":"4a90154feaee8bd24e253fd8eb87f843"}
//        // 返回码，10000为成功; remsg:返回结果描述; data:返回业务数据; 商户请求订单号;    订单状态0:已接受,1:处理中,2:处理成功,3:处理失败;  系统处理日期(yyyyMMddHHmmss));    平台流水号;  签名数据
//        // {"recode":"10000","remsg":"成功","data":{"order_no":"xxx","order_status":"xxx","process_date":"xxx","query_id":"xxx"},"signdata":""}
//        //if (!result.isSuccess()) { // 当且仅当返回码为10000时表示请求成功
//        //    throw new HfException("HfException", result.getMessageText());
//        //}
//        List<BusItemInvest> investList = investMapper.getInvestListByItemId(itemId);
//        //是否完成解冻开关
//        thawBoolean(investList, null);
//
//        for (int i = 0; i < investList.size(); i++) {
//            BusItemInvest busItemInvest = investList.get(i);
//            BusAccount busAccount = accountMapper.getBusAccountByUserId(busItemInvest.getUserId());
//            //根据investId查找红包
//            BasCoupon coupon = couponMapper.getCouponByInvestId(busItemInvest.getId());
//            //修改红包信息
//            if (null != coupon) {
//                Map couponMap = new HashMap();
//                couponMap.put("investId", null);
//                couponMap.put("useTime", null);
//                couponMap.put("userId", coupon.getUserId());
//                couponMap.put("id", coupon.getId());
//                couponMap.put("newStatus", 2);
//                couponMap.put("oldStatus", 1);
//                couponMapper.updateCouponStatus(couponMap);
//            } else {
//                coupon = new BasCoupon();
//                coupon.setAmount(BigDecimal.ZERO);
//            }
//            DealAction cancelAction = new CancelDealAction();
//            cancelAction.deal(busAccount.getUserId(), busItemInvest.getInvestDealAmount().subtract(coupon.getAmount()), item.getItemName() + "项目撤回返回投资资金");
//            dealModule.dealAction(cancelAction);
//            //根据investId查询加息券
//            BasTicket ticket = ticketMapper.getTicketByInvestId(busItemInvest.getId());
//            //修改加息券信息
//            if (null != ticket) {
//                Map ticketMap = new HashMap();
//                ticketMap.put("investId", null);
//                ticketMap.put("useTime", null);
//                ticketMap.put("userId", ticket.getUserId());
//                ticketMap.put("id", ticket.getId());
//                ticketMap.put("newStatus", 2);
//                ticketMap.put("oldStatus", 1);
//                ticketMapper.updateTicketStatus(ticketMap);
//            }
//            //修改投资的状态为撤回
//            investMapper.updateItemInvestStatus(0, 2, busItemInvest.getId());
//        }
//        Integer oldStatus = item.getItemStatus();
//        if (oldStatus == 20) {
//            itemMapper.updateItemStatus(oldStatus, ItemStatus.FULL_FAILURE, itemId);
//        } else {
//            itemMapper.updateItemStatus(oldStatus, ItemStatus.CANCEL_SUCCESS, itemId);
//        }
//        return Message.OK;
//    }

    /**
     * 前台项目列表
     *
     * @param p   分页参数
     * @param map 项目类型
     * @return
     */
    @Override
    public PageList queryByStatus(Paginator p, Map map) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        List<BasItemVo> list = itemMapper.listByStatus(map);
        for (int i = 0; i < list.size(); i++) {
            BasItemVo item = list.get(i);
            Date date = new Date();
            long a = 0L;
            if (item.getReleaseTime() != null) {
                a = item.getReleaseTime().getTime();
            }
            long b = date.getTime();
            long d = a - b;
            if (d <= 0) {
                itemMapper.updateItemStatus(ItemStatus.WAITOPEN, ItemStatus.OPEN, item.getId());
            }
            item.setCountdown(d);
            System.out.println("_______________________________" + d);
        }
        return new PageList(list);
    }

    //后台项目投资人数统计
    @Override
    public Integer countItemInvestNum(Map map) {
        return itemMapper.countItemInvestNum(map);
    }

    @Override
    public BasItemVo itemById(Integer id) {
        BasItem basItem = itemMapper.selectByPrimaryKey(id);
        BasItemVo item = new BasItemVo();
        BeanUtils.copyProperties(basItem, item);
        Date date = new Date();
        long a = 0L;
        if (item.getReleaseTime() != null) {
            a = item.getReleaseTime().getTime();
        }
        long b = date.getTime();
        long d = a - b;
        if (d <= 0) {
            itemMapper.updateItemStatus(ItemStatus.WAITOPEN, ItemStatus.OPEN, item.getId());
        }
        item.setCountdown(d);
        System.out.println("+++++++++++++++++++++++++++++++" + d);
        return item;
    }

    @Override
    public Integer sumNoFullItemNum(Map map) {
        return itemMapper.sumNoFullItemNum(map);
    }

    @Override
    public Double sumNoFullItemAccount(Map map) {
        return itemMapper.sumNoFullItemAccount(map);
    }

    @Override
    public Double sumFullItemAccountBalance(Map map) {
        return itemMapper.sumFullItemAccountBalance(map);
    }

    @Override
    public Integer countAutoInvestNum(Map map) {
        return itemMapper.countAutoInvestNum(map);
    }

    @Override
    public Integer countNoAutoInvestNum(Map map) {
        return itemMapper.countNoAutoInvestNum(map);
    }


    //根据id修改内容
    @Override
    public Integer modifyContentById(@Param("itemContent") String itemContent, @Param("id") Integer id) {
        return itemMapper.modifyContentById(itemContent, id);
    }

    //首页显示新手标单个项目
    @Override
    public BasItem getIsNewItem() {
        return itemMapper.getIsNewItem();
    }

    /**
     * 通过包ID查询包下面的标
     *
     * @param packageId 包Id
     *                  暂时不分页
     * @return
     */
    @Override
    public PageList getItemListByPackageId(Paginator p, Integer packageId) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        List<BasItem> list = itemMapper.getItemListByPackageId(packageId);
        return new PageList(list);
    }


//    /**
//     * 包初审
//     *
//     * @param eachAmount 每份金额(包表)
//     * @param content    内容(包表)
//     * @param packageId  包ID
//     */
//    @Override
//    public Object packageFirstTrial(BigDecimal eachAmount, String content, Integer packageId) {
//
//        if (eachAmount == null || content == null || packageId == null) {
//            throw new CrowdException("asset.package.parameter_isNull");
//        }
//
//        //根据包id查询标列表
//        List<BasItem> itemList = itemMapper.getItemListByPackageId(packageId);
//        Boolean allIn = true;
//        StringBuffer errorExceptionMessage = new StringBuffer("");
//        for (BasItem item : itemList) {
//            BusVerify verify = new BusVerify();
//            verify.setVerifyStatus(Byte.parseByte("1"));
//            try {
//                firstVerify(item.getId(), verify, 0, null, 2);
//            } catch (CrowdException e) {
//                errorExceptionMessage.append(ExceptionMessage.exceptionMessage.get(e.getCode()));
//                allIn = false;
//            } catch (HfException e){
//                errorExceptionMessage.append(e.getMessageText());
//                allIn = false;
//            }
//        }
//        //如果为false，通知页面有标的未通过
//        if (!allIn) {
//            Map map = new HashMap();
//            map.put("messageText", errorExceptionMessage);
//            map.put("result", "fail");
//            return map;
//        }
//        //修改标
////        itemMapper.modifyitemStatusById(ItemStatus.OPEN, packageId);//第一个参数为要修改的状态位，第二个为标Id
//
//        //拿到包的信息 把包改为 2-计划进行中
//        BasAssetsPackage assetsPackage = assetsPackageMapper.selectByPrimaryKey(packageId);
//        assetsPackage.setId(packageId);
//        assetsPackage.setEachAmount(eachAmount);
//        assetsPackage.setContent(content);
//        assetsPackage.setStatus(2);
//        assetsPackage.setUpdatetime(new Date());
//        assetsPackageMapper.updateByPrimaryKey(assetsPackage);
//
//        //找到资产下面的打包信息  标利率 itemRate，借款周期 itemCycle，周期单位 itemCycleUnit，所有标总金额 itemAccount，还款方式 itemRepayMethod
//        BasItem item = itemMapper.getItemByPackageId(packageId);
//        //生成包计划
//        BusAssetPackagePlan busAssetPackagePlan = new BusAssetPackagePlan();
//        Integer cycle =0;
//        if (item.getItemCycleUnit() == 1) {//天标
//            if (item.getItemCycle() < 30) {//小于三十天的都只添加一个计划
//                busAssetPackagePlan.setStatus(2);//状态：1-等待发布，2-投资中，3-已满标，4-已匹配审核
//                busAssetPackagePlan.setPeriods(1);//期数
//                busAssetPackagePlan =  insertPackagePlan(packageId, assetsPackage, item, busAssetPackagePlan);
//                autoInvest.basAssetsPackageMatchingAutoRule(busAssetPackagePlan);
//            } else {
//                cycle = item.getItemCycle() / 30;//这里需要确认是否会产生45天标 如果有则需需要修改判断 2017/3/30 zfw
//            }
//        } else if (item.getItemCycleUnit() == 3) //月标
//            cycle = item.getItemCycle();
//        else if (item.getItemCycleUnit() == 4) //季标
//            cycle = item.getItemCycle() * 3;
//        else if (item.getItemCycleUnit() == 5) //年标
//            cycle = item.getItemCycle() * 12;
//        else //周标
//            cycle = item.getItemCycle() / 7;
//
//        for (int i = 0; i < cycle; i++) {
//            if (i == 0) //第一期包直接变为投资中
//                busAssetPackagePlan.setStatus(2);//状态：1-等待发布，2-投资中，3-已满标，4-已匹配审核
//             else
//                busAssetPackagePlan.setStatus(1);
//
//            busAssetPackagePlan.setPeriods(i + 1);//期数
//            busAssetPackagePlan = insertPackagePlan(packageId, assetsPackage, item, busAssetPackagePlan);
//            if (i==0){
//                autoInvest.basAssetsPackageMatchingAutoRule(busAssetPackagePlan);
//            }
//        }
//        return Message.OK;
//    }

    /**
     * 资产转标
     *
     * @param sysAssetProductvo 资产对象vo
     * @param itemRate
     * @return
     */
    @Override
    public Integer assetsShiftBid(SysAssetProductVo sysAssetProductvo, BigDecimal debtServeFeeRate, BigDecimal itemRate,BigDecimal itemSingleMinInvestment) {

        BasItem item = new BasItem();
        //资产表有的字段
        item.setItemRate(itemRate);//利率
        item.setItemUserId(sysAssetProductvo.getAssetBorrowerId());//资方id
        item.setItemStatus(ItemStatus.NEW);//标为新建
        item.setItemName(sysAssetProductvo.getName());//项目名称
        item.setItemAccount(new BigDecimal(sysAssetProductvo.getAmount()));//借款金额
        item.setItemCycle(sysAssetProductvo.getTimeLimit());//借款周期
        item.setItemCycleUnit(sysAssetProductvo.getCycleUnit());//周期单位
        item.setItemRepayMethod(sysAssetProductvo.getRepayStyle());//还款方式
        item.setItemDesc(sysAssetProductvo.getDescription());//产品描述
        item.setAddip(IpUtils.get());
        item.setAddtime(new Date());

        item.setDebtTransferable(sysAssetProductvo.getDebtTransferable());//是否可债转 前台下拉选择
        item.setItemNumber(this.generaterNextNumber());//自动生成编号
        item.setEndTime(sysAssetProductvo.getEndTime());//发布时间 前台选择时间
        item.setItemIsrecommend(sysAssetProductvo.getItemIsrecommend());//起息日
        item.setFundSecurity(sysAssetProductvo.getFundSecurity());//资金安全
        item.setRiskControlMeasures(sysAssetProductvo.getRiskControlMeasures());//风控措施
        item.setItemIsalive((byte) 1);
        item.setItemIsnew(sysAssetProductvo.getItemIsnew().byteValue());
        item.setItemAddRate(Zero);
        item.setItemServeRate(Zero);
        item.setDebtServeFeeRate(debtServeFeeRate);
        item.setItemType(1);
        item.setItemOngoingAccount(Zero);
        item.setItemScale(Zero);
        item.setInvestTimes(0);
        item.setUpdateTime(new Date());
        item.setFullStatus(0);
        item.setItemSingleMinInvestment(itemSingleMinInvestment);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            item.setInterestTime(sdf.parse(sysAssetProductvo.getInterestTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        itemMapper.assetsShiftBid(item);
        Integer itemId = item.getId();
        //添加标图片附件
        SysPicture sysPicture = new SysPicture();
        sysPicture.setAddtime(new Date());
        sysPicture.setItemId(itemId);
        sysPicture.setPictureType(4);
        List<String> picList = sysAssetProductvo.getPicList();
        for (int i = 0; i < picList.size(); i++) {
            String[] list = picList.get(i).split(",");
            sysPicture.setItemPictureType(Integer.valueOf(list[1]));
            sysPicture.setPicturePath(list[0]);
            pictureMapper.insert(sysPicture);
        }
        BusVerifyLog verifyLog = new BusVerifyLog();
        verifyLog.setItemId(itemId);
        verifyLog.setAddtime(new Date());
        verifyLog.setStatus((byte) 1);
        verifyLog.setType((byte) 1);
        verifyLog.setContent("项目发标");
        verifyLog.setOperateUserId(1);//默认为系统
        verifyLogMapper.insert(verifyLog);
        return itemId;
    }

    /**
     * 生成下一个编号 格式 yyMMdd+3位递增数
     */
    public synchronized String generaterNextNumber() {

        //查出上一个新增标的编号
        String sno = itemMapper.getLastOne();
        String date = "";
        if (sno != null && sno.length() > 0) {
            date = sno.substring(0, 8);
        }
        String id = null;
        String now = StringUtils.getFullTime().substring(0, 8);
        if (sno == null || !now.equals(date)) {
            id = now + "001";
        } else {
            String num = RadixHelper.num2Radix(10, 1 + Integer.valueOf(sno.substring(8, 11)));
            int count = SERIAL_NUMBER.length() - num.length();
            StringBuilder sb2 = new StringBuilder();
            for (int i = 0; i < count; i++) {
                sb2.append("0");
            }
            sb2.append(num);
            id = now + sb2.toString();
        }
        return id;
    }

    public BusAssetPackagePlan insertPackagePlan(Integer packageId, BasAssetsPackage assetsPackage, BasItem item, BusAssetPackagePlan assetPackagePlan) {
        BusAssetPackagePlan busAssetPackagePlan = new BusAssetPackagePlan();
        busAssetPackagePlan.setAssetPackageId(packageId);//包Id
        busAssetPackagePlan.setPackagePlanName(assetsPackage.getPackageName()+assetPackagePlan.getPeriods()+"期");//包计划名称
        busAssetPackagePlan.setRate(item.getItemRate());//利率
        busAssetPackagePlan.setCycleUnit(item.getItemCycleUnit());//周期单位：1-天，2-月，3-季，4-年
        busAssetPackagePlan.setAmount(item.getItemAccount());//金额
        busAssetPackagePlan.setRepayMethod(item.getItemRepayMethod());//还款方式 1-一次性还款 2-等额本息 3-先息后本
        busAssetPackagePlan.setCycle(item.getItemCycle());//周期
        busAssetPackagePlan.setAddtime(new Date());
        busAssetPackagePlan.setAddip(IpUtils.get());
        busAssetPackagePlan.setOngoingAccount(Zero);
        busAssetPackagePlan.setScale(Zero);
        busAssetPackagePlan.setStatus(assetPackagePlan.getStatus());
        busAssetPackagePlan.setPeriods(assetPackagePlan.getPeriods());
        busAssetPackagePlanMapper.insert(busAssetPackagePlan);
        return busAssetPackagePlan;
    }
}
